﻿package meteo; // Always use packages. Never use default package.

import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import core.HeatDb;

/**
 * Very simplistic servlet that generates plain text. Uses the @WebServlet
 * annotation that is supported by Tomcat 7 and other servlet 3.0 containers.
 *
 * From <a href="http://courses.coreservlets.com/Course-Materials/">the
 * coreservlets.com tutorials on servlets, JSP, Struts, JSF 2.x, Ajax, jQuery,
 * GWT, Spring, Hibernate/JPA, Hadoop, and Java programming</a>.
 */

@WebServlet("/heat")
public class HeatServlet extends HttpServlet {

	private final static String HEAD_CONTENTS =
     "<!DOCTYPE html>	<html>	  <head>	    <title>Heat</title>"
	    + "<link rel=\"stylesheet\" type=\"text/css\" href=\"/_static/css/screen.css\" />"
	    + "<link rel=\"stylesheet\" href=\"//www.google.com/cse/style/look/default.css\" type=\"text/css\" />"
	    + "<link href='//fonts.googleapis.com/css?family=Open+Sans:300,400' rel='stylesheet' type='text/css'>"
	    + "<script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js\"></script>"
	    + "<script id=\"jqueryui\" src=\"//ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js\" defer async></script>"
	    + " <script src=\"//www.google.com/jsapi?key=AIzaSyCZfHRnq7tigC-COeQRmoa9Cxr0vbrK6xw\"></script>"
	   + " <!--[if lt IE 9]>"
	   + " <script src=\"//html5shiv.googlecode.com/svn/trunk/html5.js\"></script>"
	  + "  <![endif]-->"
	+ "  </head>"
	 + " <br/> "
	 + " <body class=\"docs framebox_body\">"

	 + "<script type=\"text/javascript\" src=\"//www.google.com/jsapi\"></script>"

	 + "<script type=\"text/javascript\">"

	 + "google.load('visualization', '1', {packages: ['table', 'gauge', 'intensitymap', 'corechart']});"
	+ "google.setOnLoadCallback(drawMouseoverVisualization);"
	+ "  var barsVisualization;"
	+ "  function drawMouseoverVisualization() {"
	 + "   var data = new google.visualization.DataTable();"
	 + "   data.addColumn('string', 'Date');"
	 + "   data.addColumn('number', 'Temperature');"
	 + " data.addRows([";

	   private final static String BODY_CONTENTS =  " ]); "

//	    data.addRows([
//	      ['2005', 3.6],
//	      ['2006', 4.1],
//	      ['2007', 3.8],
//	      ['2008', 3.9],
//	      ['2009', 4.6]
//	    ]);

      + "  barsVisualization = new google.visualization.ColumnChart(document.getElementById('mouseoverdiv'));"
	   + "  barsVisualization.draw(data, null);"

	    // Add our over/out handlers.
	    + " google.visualization.events.addListener(barsVisualization, 'onmouseover', barMouseOver);"
	   + "  google.visualization.events.addListener(barsVisualization, 'onmouseout', barMouseOut);"
	   + "  }"

	   + "function barMouseOver(e) {"
	   + "  barsVisualization.setSelection([e]);"
	   + " }"

	  + " function barMouseOut(e) {"
	    + " barsVisualization.setSelection([{'row': null, 'column': null}]);"
	    + " }"
	 + "</script>"

	 + "<div id='mouseoverdiv' style=\"height: 400px;\">&nbsp;</div>"

	 + "</body>"
	 + "</html>";

	/**
	 *
	 */
	private static final long serialVersionUID = -8355240584559713699L;

	@Override
	public void doGet(final HttpServletRequest request, final HttpServletResponse response)
		throws ServletException, IOException {
	    final String reponse =
            HEAD_CONTENTS
            + createTemprateAsString()
           // + "   ['2005', 3.6], ['2006', 4.1],     ['2007', 3.8],     ['2008', 3.9],  ['2009', 4.6]"
            + BODY_CONTENTS;

		response.getWriter().print(reponse);
	}

	String createTemprateAsString() {
	    final String template = "[''{0}'', {1}],";
	    final StringBuilder builder = new StringBuilder();
	    try {
            HeatDb.connect();



            final Set<Integer> ids = HeatDb.getDataIds();
            final Set<String> data = new HashSet<String>();
            final Set<Integer> unicId = new HashSet<Integer>();
            int cnt = 20;
            for (final Integer id : ids) {
                try {
                    if (!data.contains(HeatDb.getDate(id))) {
                        data.add(HeatDb.getDate(id));
                        unicId.add(id);
                    }
                } catch (final IOException e) {
                    e.printStackTrace();
                }

                if (--cnt < 0) {
                    break;
                }
            }

            final Iterator<Integer> iterator = unicId.iterator();
            cnt = 20;
            Integer id;
            while (--cnt >= 0 && iterator.hasNext()) {
                id = iterator.next();
                System.out.println("id " +  id);
                try {
                    final String temp = HeatDb.getTemperature(id);
                    if (temp != null && !temp.isEmpty()) {
                        System.out.println("temp " +  temp);
                        builder.append(
                            MessageFormat.format(
                                template,
                                HeatDb.getDate(id),
                                temp
                            )
                        );
                    }
                } catch (final IOException e) {
                    e.printStackTrace();
                }
            }

            if (cnt != 20) {
                builder.deleteCharAt(builder.length() - 1);
                System.out.println("builder " + builder.toString());
            }
        } catch (final IOException e) {
            e.printStackTrace();
        }

	    return builder.toString();

	}
}
